package com.mg.exception;

import com.mg.dto.SimpleResult;
import com.mg.utils.JsonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by 研发二科 王永梅 on 2016/12/30.
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LogManager.getLogger(GlobalExceptionHandler.class.getName());

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception ex, HttpServletResponse response) throws Exception {
        String DEFAULT_ERROR_VIEW = "error";
        /* 区分ajax */
        boolean isAjax = req.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(req.getHeader("X-Requested-With").toString());
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", ex);
        mav.addObject("url", req.getRequestURL());

        if (!isAjax) {
            mav.setViewName(DEFAULT_ERROR_VIEW);
            return mav;
        } else {
            PrintWriter out = null;
            SimpleResult result = new SimpleResult();
            result.setSuccess(false);
            ex.printStackTrace();
            logger.error(ex);
            result.setErrorMessage(ex.getMessage());
            result.setMsg(ex.getMessage());
            result.setErrorCode("ERROR");
            try {
                out = response.getWriter();
                req.setCharacterEncoding("utf-8");
                response.setContentType("text/plain;charset=utf-8");
                String json = JsonUtils.toAgentJson(result);
                out.print(json.substring(0, json.length()));
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                out.close();
            }


            return null;
        }

    }


}